package com.heima.media.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.dto.UserThreadLocalUtil;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.media.dto.ContentDto;
import com.heima.media.dto.ImageDto;
import com.heima.media.dto.WmNewsDto;
import com.heima.media.dto.WmNewsPageDto;
import com.heima.media.entity.WmNews;
import com.heima.media.entity.WmNewsMaterial;
import com.heima.media.mapper.WmNewsMapper;
import com.heima.media.service.IAuditService;
import com.heima.media.service.IWmNewsMaterialService;
import com.heima.media.service.IWmNewsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import javax.json.Json;
import java.util.*;

/**
 * <p>
 * 自媒体图文内容信息表 服务实现类
 * </p>
 *
 * @author hsg
 * @since 2022-06-28
 */
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements IWmNewsService {
    @Autowired
    private IWmNewsMaterialService wmNewsMaterialService;
    @Override
    public ResponseResult listByCondition(WmNewsPageDto dto) {
        User user = UserThreadLocalUtil.get();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();
        //        状态
        if(dto.getStatus()!=null){
            queryWrapper.eq(WmNews::getStatus,dto.getStatus());
        }
        //        开始时间
        if (dto.getBeginPubDate()!=null) {
            queryWrapper.ge(WmNews::getPublishTime,dto.getBeginPubDate());
        }
        //      结束时间
        if (dto.getEndPubDate()!=null) {
            queryWrapper.le(WmNews::getPublishTime,dto.getEndPubDate());
        }
        //      频道
        if (dto.getChannelId()!=null) {
            queryWrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }
        //     关键字
        if (StringUtils.isNotBlank(dto.getKeyword())) {
            queryWrapper.like(WmNews::getTitle,dto.getKeyword());
        }
        //     隐藏条件：1、排序 2、当前登录人
        queryWrapper.eq(WmNews::getUserId,user.getUserId());

        queryWrapper.orderByDesc(WmNews::getPublishTime);


        IPage<WmNews> page = new Page<>(dto.getPage(),dto.getSize());
        IPage<WmNews> page1 = this.page(page, queryWrapper);

        return new PageResponseResult(dto.getPage(),dto.getSize(),page1.getTotal(),page1.getRecords());
    }

    @Override
    public ResponseResult submit(WmNewsDto dto) {
        //判断是否已经登录
        User user = UserThreadLocalUtil.get();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //判断是否存在id
        Integer id = dto.getId();
        if (id!=null) {
            // 根据自媒体文章id 删除已关联的素材关系
            deleteRelation(dto.getId());
        }
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto,wmNews);
        wmNews.setUserId(user.getUserId());
        wmNews.setCreatedTime(new Date());
        wmNews.setImages(JSON.toJSONString(dto.getImages()));
        List<ImageDto> conentImages = getImagesFromContent(dto.getContent());
        //自动设置封面图片
        if(dto.getType()==-1){
            int size = conentImages.size();
            if(size<=0){
                //无图
                wmNews.setType(0);
            }else if(size>0&&size<3){
                wmNews.setType(1);
                // 截取内容图片中的1个对象作为封面
                List<ImageDto> imageDtoList = conentImages.subList(0, 1);
                wmNews.setImages(JSON.toJSONString(imageDtoList));
            }else{
                wmNews.setType(3);
                //截取内容图片中的3个对象作为封面
                List<ImageDto> imageDtoList = conentImages.subList(0, 3);
                wmNews.setImages(JSON.toJSONString(imageDtoList));
            }
        }
        //新增文章或者修改文章
        this.saveOrUpdate(wmNews); //自动判断是否有id  如果有ID就是修改 如果没有id就新增
        //判断是否为草稿,1则不是草稿,需要关联内容/封面中的图片与素材的关系
        if(dto.getStatus()==1){ //提交为1，不是草稿
            // 保存文章内容图片和素材之间的关系
            saveRelation(conentImages,wmNews.getId(),0);
            //保存文章封面图片和素材之间的关系
            List<ImageDto> imageDtoList = JSON.parseArray(wmNews.getImages(), ImageDto.class);
            saveRelation(imageDtoList,wmNews.getId(),1);
            //自动审核，调用审核的方法
            auditService.audit(wmNews);
        }
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        User user = UserThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        WmNews wmNews = this.getById(dto.getId());
        if(wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if(dto==null||dto.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if(user.getUserId().intValue()!=wmNews.getUserId().intValue()){
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }


        wmNews.setEnable(dto.getEnable()==1?true:false);
        this.updateById(wmNews);
        //除了管理端新闻要下架，客户端文章也要下架
        Long articleId = wmNews.getArticleId();
        Map map = new HashMap();
        map.put("articleId",articleId);
        map.put("enable",dto.getEnable()==1?true:false);
        kafkaTemplate.send(topic,JSON.toJSONString(map));
        return ResponseResult.okResult();
    }
    @Value("${topic.upDownTopic}")
    private String topic;
    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;
    @Autowired
    private IAuditService auditService;
    //保存文章内容图片、封面图片与素材的关系
    private void saveRelation(List<ImageDto> imageDtoList, Integer newsId, int type) { //type 0:内容   type:1 封面
        int i = 0;
        for (ImageDto imageDto : imageDtoList) {
            WmNewsMaterial newsMaterial = new WmNewsMaterial();
            newsMaterial.setMaterialId(imageDto.getId());
            newsMaterial.setNewsId(newsId);
            newsMaterial.setType(type);
            newsMaterial.setOrd(i++);
            wmNewsMaterialService.save(newsMaterial);
        }
    }
    //从内容中获取所有图片
    private List<ImageDto> getImagesFromContent(String content) {
        List<ImageDto> imageDtoList = new ArrayList<>();
        List<ContentDto> contentDtos = JSON.parseArray(content, ContentDto.class);
        for (ContentDto contentDto : contentDtos) {
            if (contentDto.getType().equals("image")) {
                ImageDto imageDto = new ImageDto();
                imageDto.setId(contentDto.getId());
                imageDto.setUrl(contentDto.getValue());
                imageDtoList.add(imageDto);
            }
        }
        return imageDtoList;
    }
    private void deleteRelation(Integer newsId) {
        LambdaQueryWrapper<WmNewsMaterial> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmNewsMaterial::getNewsId,newsId);
        wmNewsMaterialService.remove(queryWrapper);
    }
}
